<template>
  <u-popup v-if="show" v-model="show" mode="bottom" :mask="false" @close="bindClose()">
    <z-paging v-if="dataList.length && userMessage.referenceImage " class="z-paging"  ref="paging" v-model="dataList" :fixed="false" :show-refresher-when-reload="true" :refresher-complete-delay="1000" @query="queryList">
      <!-- 如果希望其他view跟着页面滚动，可以放在z-paging标签内 -->
      <view v-for="(item, index) in dataList" :key="index" class="item">
        <view class="item-title text-base">{{ item.title }}</view>
        <view class="item-detail">{{ item.detail }}</view>
        <view class="item-line"></view>
      </view>
    </z-paging>

    <div class="ai-message-content">
      <div class="img-content">
        <div v-if="!userMessage.prompt" class="img-bg-content">
          <image v-if="upImg" class="up-img" :src="upImg" mode="aspectFit"></image>
          <div v-else class="img-content-body">
            <div class="t1">上传参考图(可选)</div>
            <div class="t2">请确保图片已授权</div>
          </div>
        </div>

        <div v-else class="rst-content">
          <div class="rst-content-body">
            <div class="rst-user">
              <image v-if="userMessage.referenceImage" class="user-img" :src="userMessage.referenceImage" mode="aspectFit"></image>
              <div class="time-txt">
                <div class="time">{{ userMessage.time }}</div>
                <u-read-more>
                  <div class="txt">{{ userMessage.prompt }}</div>
                </u-read-more>
              </div>
            </div>

            <div class="rst-ai">
              <div class="ai-tip">以下是为你生成的图片：</div>
              <div class="rst-img">
                <image class="rst-img-item" :src="userMessage.value.multipleImages" mode="aspectFit"></image>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="bottom-content">
        <div class="ai-style-templates">
          <div v-for="(item, index) in templates" :key="index" class="ai-style-item" @click="bindTemplate(item, index)">
            <image class="ai-template-image" :src="item.referenceImage" mode="aspectFill"></image>
            <view class="title">{{ item.title }}</view>
            <view v-if="item.isHot" class="tag">热门</view>
            <image v-if="index === templateIndex" class="go-image" src="https://cos.aitshirt.cn/app-icon/%E7%BB%84%2013174%402x.png"></image>
          </div>
        </div>
        <div class="ai-ratios-templates">
          <div class="ai-ratios-content">
            <wd-picker v-model="ratio" :columns="ratioList" label="比例" custom-view-class="custom-class" />
          </div>
        </div>

        <div class="ipt-boyd">
          <div class="upload-img" @click="uploadImg">
            <image class="upload-icon" src="https://cos.aitshirt.cn/%E7%BB%84%201765%402x.png"></image>
          </div>
          <div class="ipt-content">
            <u-input v-model="text" placeholder="请描述您想要的素材..."></u-input>
            <i class="iconfont icon-shang-1" @click="submit"></i>
          </div>
        </div>
      </div>
    </div>
  </u-popup>
</template>
<script setup lang="ts">
import { onMounted, ref, shallowRef, watch } from "vue";
import { getTheListOfAIStyleTemplates, getPoints, getAspectRatio, aiSubmitTheAIGeneratedTask, aiGetById, getAiList } from '@/api/designApi';
import { chooseLocalImgAndUpload } from '@/utils/QnUpload';
import dayjs from 'dayjs';

const emit = defineEmits(['colorChange']);

const paging = shallowRef(null);
const dataList = shallowRef([]);

// @query所绑定的方法不要自己调用！！需要刷新列表数据时，只需要调用(this.$refs['pagingX'] as ZPagingXComponentPublicInstance).reload()即可
function queryList(pageNo: number, pageSize: number) {
  const params = {
    pageNum: pageNo,
    pageSize: pageSize,
  };
  // 此处请求仅为演示，请替换为自己项目中的请求
  getAiList(params).then((res) => {
    // 将请求结果通过complete传给z-paging处理，同时也代表请求结束，这一行必须调用
    paging.value.complete(res['data'] as any[]);
  });
}

watch(() => paging.value, () => {
  if (paging.value) {
    paging.value.reload();
  }
})
const userMessage = ref<any>({
  referenceImage: '',
  prompt: '',
  time: '',
  multipleImages: '',
});

const text = ref('');
const show = ref(true);
const submit = () => {
  if (!text.value) return;
  aiSubmitTheAIGeneratedTask({
    aspectRatio: ratio.value,
    prompt: text.value,
    referenceImage: upImg.value,
  }).then((res) => {
    // console.log('aiSubmitTheAIGeneratedTask', res);
    userMessage.value = {
      aspectRatio: ratio.value,
      prompt: text.value,
      referenceImage: upImg.value,
      time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    };
    text.value = '';
    upImg.value = '';

    getDetailById(res.data);
  });
};

const open = (color: any) => {
  show.value = true;
};

const templates = shallowRef([]);
const templateIndex = ref(-1);
const ratioList = shallowRef([]);
const ratio = ref<number>(1);

onMounted(() => {
  // 获取AI风格模版列表
  getTheListOfAIStyleTemplates().then((res) => {
    // console.log('getTheListOfAIStyleTemplates', res);
    templates.value = res.data;
  });
  getAspectRatio().then((res) => {
    // console.log('getAspectRatio', res);
    ratioList.value = Object.values(res.data).map((k) => k); //.map(k => ({label: k, value: k}));
    ratio.value = ratioList.value[0];
  });

  checkPoints();
});

const checkPoints = () => {
  // 获取用户身上AI总次数
  getPoints().then((res) => {
    // console.log('getPoints', res);
  });
};

const bindTemplate = (item, index) => {
  templateIndex.value = index;
  upImg.value = item.referenceImage;
  text.value = item.prompt;
};

const getDetailById = (id) => {
  uni.showLoading({ title: '图片生成中', mask: true });
  aiGetById({ id }).then((res) => {
    // console.log('res', res);
    if (res.data.jobType === 1 || res.data.jobType === 0) {
      setTimeout(() => {
        getDetailById(id);
      }, 2000);
    } else if (res.data.jobType === 2) {
      uni.hideLoading();
      userMessage.value.multipleImages = res.data.multipleImages;
    } else {
      uni.hideLoading();
      uni.showToast({
        title: '生成失败, 请稍后再试',
        icon: 'none',
      });
    }
  });
};

const upImg = ref('');
const uploadImg = () => {
  chooseLocalImgAndUpload().then((res) => {
    // console.log('chooseLocalImgAndUpload', res);
    if (res) {
      upImg.value = res;
    }
  });
};

defineExpose({
  open,
});

const bindClose = () => {
  show.value = false;
};
</script>

<style scoped lang="scss">
.ai-message-content {
  position: relative;
  display: flex;
  width: 100vw;
  height: 100vh;
}

.img-content {
  display: flex;
  flex: 1;
  width: 100%;
  height: calc(100vh - 378rpx);
  background: rgba(255, 0, 0, 0.18);
  align-items: center;
  justify-content: center;

  .img-bg-content {
    width: 548rpx;
    height: 760rpx;
    background: #f3f7f8;
    box-shadow: 0rpx 2rpx 8rpx 2rpx rgba(0, 0, 0, 0.09);
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    border: 1rpx solid #bebebe;
    display: flex;
    align-items: center;
    justify-content: center;
    .up-img {
      width: 500rpx;
      margin: auto;
    }
  }
  .img-content-body {
    .t1 {
      height: 38rpx;
      font-weight: 400;
      font-size: 28rpx;
      color: #6f6f6f;
      line-height: 38rpx;
      text-align: center;
    }
    .t2 {
      height: 28rpx;
      font-weight: 400;
      font-size: 20rpx;
      color: #a4a4a4;
      line-height: 28rpx;
      text-align: center;
      margin: 10rpx 0 0;
    }
  }
}

.bottom-content {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 378rpx;
  background: #ffffff;
  box-shadow: 0rpx -4rpx 10rpx 2rpx rgba(0, 0, 0, 0.08);
  border-radius: 16rpx 16rpx 0rpx 0rpx;

  .ai-style-templates {
    display: flex;
    gap: 16rpx;
    padding: 18rpx 32rpx 16rpx;
    //overflow-x: auto;
    .ai-style-item {
      position: relative;
      .ai-template-image {
        width: 124rpx;
        height: 146rpx;
        background: #ffffff;
        border-radius: 8rpx 8rpx 8rpx 8rpx;
        //border: 2rpx solid #707070;
      }
      .title {
        position: absolute;
        left: 50%;
        bottom: 12rpx;
        transform: translate(-50%, 0);
        height: 28rpx;
        font-weight: 400;
        font-size: 20rpx;
        color: #ffffff;
        line-height: 28rpx;
        text-align: center;
      }

      .tag {
        position: absolute;
        left: 0;
        top: 0;
        width: 54rpx;
        height: 34rpx;
        background: linear-gradient(90deg, #f32f1a 0%, #f68a2d 100%);
        border-radius: 8rpx 0rpx 8rpx 0rpx;
        font-weight: 400;
        font-size: 20rpx;
        color: #ffffff;
        line-height: 34rpx;
        text-align: center;
      }

      .go-image {
        position: absolute;
        right: 8rpx;
        top: 8rpx;
        width: 28rpx;
        height: 28rpx;
      }
    }
  }

  .ai-ratios-templates {
    width: 100%;
    height: 90rpx;
    border-bottom: 1rpx solid #e4e4e4;
    border-top: 1rpx solid #e4e4e4;
    .ai-ratios-content {
      width: 240rpx;
      border: 2rpx solid #f8f8f8;
      font-weight: 400;
      font-size: 24rpx;
      color: #222222;
      line-height: 48rpx;
      :deep(.wd-cell__wrapper) {
        padding: 0 !important;
      }
      .custom-class {
        background: red !important;
      }
    }
  }

  .ipt-boyd {
    display: flex;
    align-items: center;
    margin-top: 16rpx;
    padding: 0 32rpx;
    gap: 16rpx;
    .upload-img {
      width: 60rpx;
      height: 64rpx;
      background: #f3f7f8;
      border-radius: 30rpx 30rpx 30rpx 30rpx;
      border: 2rpx solid #f3f7f8;
      .upload-icon {
        width: 24rpx;
        height: 24rpx;
        margin: 18rpx 20rpx;
      }
    }
    .ipt-content {
      display: flex;
      align-items: center;
      width: 612rpx;
      height: 64rpx;
      border-radius: 8rpx 8rpx 8rpx 8rpx;
      border: 2rpx solid #c2c2c2;
      padding: 0 16rpx 0 24rpx;

      font-weight: 400;
      font-size: 24rpx;
      color: #6f6f6f;
      line-height: 64rpx;
      text-align: left;

      .icon-shang-1 {
        margin-left: auto;

        width: 48rpx;
        height: 48rpx;
        background: #f3f7f8;
        border-radius: 50%;
        font-size: 24rpx;
        color: #222222;
        text-align: center;
        line-height: 48rpx;
      }
    }
  }
}

.rst-content {
  .rst-content-body {
    .rst-user {
      padding: 20rpx 32rpx;
      display: flex;
      gap: 24rpx;
      background: #ffffff;
      .user-img {
        flex-shrink: 0;
        width: 108rpx;
        height: 108rpx;
        border-radius: 8rpx 8rpx 8rpx 8rpx;
      }
      .time-txt {
        display: flex;
        flex-direction: column;
        gap: 16rpx;
        .time {
          font-weight: 400;
          font-size: 24rpx;
          color: #6f6f6f;
          line-height: 32rpx;
        }
        .text {
          font-weight: 400;
          font-size: 24rpx;
          color: #222222;
          line-height: 34rpx;
        }
      }
    }
    .rst-ai {
      margin: 10rpx 32rpx;
      background: #f3f7f8;
      border-radius: 8rpx 8rpx 8rpx 8rpx;
      padding: 16rpx;
      .ai-tip {
        font-weight: 400;
        font-size: 24rpx;
        color: #222222;
        line-height: 32rpx;
        margin: 16rpx 0 20rpx;
      }
      .rst-img {
        width: 500rpx;
        margin: auto;
      }
    }
  }
}
</style>
